<?php
/**
 *
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2019/5/28 14:36
 * @copyright PanxSoft Inc.
 */

namespace App\Http\Controllers\WebView\V1;


use App\Http\Controllers\ApiController;
use App\Http\Requests\WebView\V1\WishList\WishListStoreRequest;
use App\Models\User;
use App\Models\WishList;
use App\Services\Utils\Guard;
use App\Services\Utils\Transaction;
use Illuminate\Http\Request;

class WishListController extends ApiController
{
    const ROUTES = [
        'index'    => 'webview.v1.wish-list.index',
        'create'    => 'webview.v1.wish-list.create',
        'store'    => 'webview.v1.wish-list.store',
    ];

    /**
     * @param Request $request
     *
     * @return array|\Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        /** @var User $user */
        $user = Guard::user();

        $wish_list = $this->userLastWishList($user);

        return $this->response(compact('wish_list'));
    }

    /**
     * @return array|\Illuminate\Http\Response
     */
    public function create()
    {
        /** @var User $user */
        $user = Guard::user();

        $realized_wish_lists = $this->getRealizedWishLists($user);

        return $this->response(compact('realized_wish_lists'));
    }

    /**
     * @param WishListStoreRequest $request
     *
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function store(WishListStoreRequest $request)
    {
        /** @var User $user */
        $user = Guard::user();

        $wish_list = Transaction::handle(function () use ($user, $request) {
            /** @var WishList $wish_list */
            $wish_list = (new WishList)->updateOrCreate([
                'user_id' => $user->getKey()
            ], [
                'content' => $request->input('content')
            ]);

            $this->checkUnless($wish_list->is_realized, 'your wish already realized');

            return $wish_list;
        });

        return $this->response(compact('wish_list'));
    }

    /**
     * @param User $user
     *
     * @return WishList|null
     */
    private function userLastWishList(User $user): ?WishList
    {
        /** @var WishList $wish_list */
        $wish_list = $user
            ->wishLists()
            ->oldest()
            ->first();

        return $wish_list;
    }

    /**
     * @param User $user
     *
     * @return WishList[]|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    private function getRealizedWishLists(User $user)
    {
        $wish_lists = (new WishList)
            ->where('user_id', '<>', $user->getKey())
            ->where('is_realized', WishList::IS_REALIZED)
            ->with('user')
            ->oldest()
            ->get();

        $wish_lists->each(function (WishList $wishList) {
            $wishList->user->makeHidden('phone')->append('asterisk_phone');
        });

        return $wish_lists;
    }
}